package org.xian.bio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class BIOClient {
    public static void main(String[] args) {
        int port = 8080;
        String host = "192.168.128.10";

        Scanner scanner = new Scanner(System.in);
        Socket socket = null;

        BufferedReader reader = null;
        PrintWriter writer = null;
        try {
            // 和服务端建立 Socket 连接
            socket = new Socket(host, port);
            // Socket 的输入和输出流：输入是服务端发来的 输出是发到服务端的。
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            writer = new PrintWriter(socket.getOutputStream(), true);
            // 将控制台的数据发送到 Server
            while (scanner.hasNextLine()){
                String scannerInput = scanner.nextLine();
                // 将控制台的内容发到服务端
                writer.println(scannerInput);
                // 阻塞等待服务端的返回
                String response = reader.readLine();
                System.out.println("Server Response -->" + response);
                if ("bye".equals(scannerInput)) break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(reader!=null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(writer != null){
                writer.close();
            }
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
